import * as React from 'react'
import { FoldBoxGroupContextProvider } from './context'
import type { FoldBoxGroupProps } from './interface'

const FoldBoxGroup: React.FC<FoldBoxGroupProps> = props => {
    const [value, setValue] = React.useState(props.defaultValue)

    const { children } = props

    const childrenToRender = children

    const onFoldBoxChange = (val: any) => {
        const lastValue = value
        if (!('value' in props)) {
            setValue(val)
        }
        const { onChange } = props
        if (onChange && val !== lastValue) {
            onChange(val)
        }
    }

    return (
        <div>
            <FoldBoxGroupContextProvider
                value={{
                    onChange: onFoldBoxChange,
                    value,
                }}
            >
                {childrenToRender}
            </FoldBoxGroupContextProvider>
        </div>
    )
}

export default FoldBoxGroup
